#leetcode题目8：字符串转换整数
#难度：中等
#时间复杂度：O(n)
#空间复杂度：O(1)
#解题思路：模拟
#见b站

import re

class Solution:
    def myAtoi(self, s: str) -> int:
        stripS=s.strip()

        if stripS=="" or stripS=="-" or stripS=="+":
            return 0
        
        s1=re.match(r"[^\d]+", stripS.lstrip("-").lstrip("+"))

        if s1!=None:
            return 0
        else:
            s1=re.search("\-*\+*\d+", stripS).group()

        if s1[0:2]=="--" or s1[0:2]=="++" or s1[0:2]=="+-":
            return 0
        
        result=int(s1)
        if result>0:
            if result>2**31-1:
                return 2**31-1
            else:
                return result
        else:
            if result<-2**31:
                return -2**31
            else:
                return result

    


#测试数据
s="42"
#预期输出：42
solution=Solution()
print(solution.myAtoi(s))

s="   -42"
#预期输出：-42
solution=Solution()
print(solution.myAtoi(s))

s="4193 with words"
#预期输出：4193
solution=Solution()
print(solution.myAtoi(s))

s="words and 987"
#预期输出：0
solution=Solution()
print(solution.myAtoi(s))

s="-91283472332"
#预期输出：-2147483648
solution=Solution()
print(solution.myAtoi(s))

